import { apiService } from './api';
import { useAuthStore } from '../stores/authStore';

// 认证相关类型定义
export interface LoginRequest {
  username: string;
  password: string;
  rememberMe?: boolean;
}

// 后端实际返回的登录响应类型
interface BackendLoginResponse {
  accessToken: string;
  refreshToken: string;
  tokenType: string;
  expiresIn: number;
  user: {
    id: string;
    username: string;
    email: string;
    displayName: string;
    orgId: string;
    status: number; // 1: active, 0: inactive
  };
}

export interface LoginResponse {
  token: string;
  refreshToken?: string;
  user: User;
  expiresIn: number;
}

export interface User {
  id: string;
  username: string;
  name: string;
  email?: string;
  avatar?: string;
  roles: string[];
  permissions: string[];
  organizationId?: string;
  organizationName?: string;
  departmentId?: string;
  departmentName?: string;
  tenantId: string;
  status: 'active' | 'inactive' | 'locked';
  lastLoginTime?: string;
  createdTime: string;
}

export interface RegisterRequest {
  username: string;
  password: string;
  confirmPassword: string;
  email: string;
  name: string;
  organizationId?: string;
  departmentId?: string;
}

export interface ChangePasswordRequest {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

export interface ResetPasswordRequest {
  email: string;
}

export interface UpdateProfileRequest {
  name?: string;
  email?: string;
  avatar?: string;
  phone?: string;
}

// 认证服务类
class AuthService {
  // 用户登录
  async login(credentials: LoginRequest): Promise<LoginResponse> {
    try {
      // 修正API路径，baseURL已经是/api/v1，所以这里只需要/auth/login
      const response = await apiService.post<BackendLoginResponse>('/auth/login', credentials);
      
      // 适配后端返回的数据格式到前端期望的格式
      const adaptedResponse: LoginResponse = {
        user: {
          ...response.user,
          name: response.user.displayName, // 后端返回displayName，前端期望name
          tenantId: 'default', // 设置默认租户ID
          status: response.user.status === 1 ? 'active' : 'inactive', // 状态转换
          createdTime: new Date().toISOString(),
          organizationId: response.user.orgId,
          roles: [],
          permissions: []
        },
        token: response.accessToken, // 后端返回accessToken，前端期望token
        refreshToken: response.refreshToken,
        expiresIn: response.expiresIn
      };
      
      // 登录成功后更新认证状态
      const authStore = useAuthStore.getState();
      authStore.login(adaptedResponse.user, adaptedResponse.token);
      
      return adaptedResponse;
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  }

  // 用户注册
  async register(userData: RegisterRequest): Promise<User> {
    return apiService.post('/api/auth/register', userData);
  }

  // 用户登出
  async logout(): Promise<void> {
    try {
      await apiService.post('/api/auth/logout');
    } catch (error) {
      // 即使后端登出失败，也要清除本地状态
      console.warn('Backend logout failed:', error);
    } finally {
      // 清除本地认证状态
      const authStore = useAuthStore.getState();
      authStore.logout();
    }
  }

  // 获取当前用户信息
  async getCurrentUser(): Promise<User> {
    return apiService.get('/auth/me');
  }

  // 刷新Token
  async refreshToken(): Promise<{ token: string; expiresIn: number }> {
    const response = await apiService.post('/auth/refresh-token');
    
    // 适配后端返回的数据格式：accessToken -> token
    const responseData = response as any;
    const adaptedResponse = {
      token: responseData.accessToken || responseData.token, // 兼容两种格式
      expiresIn: responseData.expiresIn || 0
    };
    
    // 更新本地Token
    const authStore = useAuthStore.getState();
    if (adaptedResponse.token && authStore.user) {
      authStore.login(authStore.user, adaptedResponse.token);
    }

    return adaptedResponse;
  }

  // 修改密码
  async changePassword(passwordData: ChangePasswordRequest): Promise<void> {
    return apiService.post('/auth/change-password', passwordData);
  }

  // 重置密码
  async resetPassword(resetData: ResetPasswordRequest): Promise<void> {
    return apiService.post('/auth/reset-password', resetData);
  }

  // 确认重置密码
  async confirmResetPassword(token: string, newPassword: string): Promise<void> {
    return apiService.post('/auth/confirm-reset-password', {
      token,
      newPassword
    });
  }

  // 更新用户资料
  async updateProfile(profileData: UpdateProfileRequest): Promise<User> {
    const updatedUser = await apiService.put('/auth/profile', profileData);
    
    // 更新本地用户信息
    const authStore = useAuthStore.getState();
    authStore.updateUser(updatedUser);
    
    return updatedUser as User;
  }

  // 上传头像
  async uploadAvatar(file: File): Promise<{ avatarUrl: string }> {
    const formData = new FormData();
    formData.append('avatar', file);
    
    const response = await apiService.post('/auth/upload-avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    // 更新本地用户头像
    const authStore = useAuthStore.getState();
    if (response && authStore.user && typeof response === 'object' && 'avatarUrl' in response) {
      authStore.updateUser({ ...authStore.user, avatar: (response as any).avatarUrl });
    }

    return (response as { avatarUrl: string }) || { avatarUrl: '' };
  }

  // 验证Token有效性
  async validateToken(): Promise<boolean> {
    try {
      await this.getCurrentUser();
      return true;
    } catch (error) {
      return false;
    }
  }

  // 检查用户名是否可用
  async checkUsernameAvailable(username: string): Promise<{ available: boolean }> {
    return apiService.get('/auth/check-username', { username });
  }

  // 检查邮箱是否可用
  async checkEmailAvailable(email: string): Promise<{ available: boolean }> {
    return apiService.get('/auth/check-email', { email });
  }

  // 发送邮箱验证码
  async sendEmailVerificationCode(email: string): Promise<void> {
    return apiService.post('/auth/send-verification-code', { email });
  }

  // 验证邮箱验证码
  async verifyEmailCode(email: string, code: string): Promise<{ valid: boolean }> {
    return apiService.post('/auth/verify-email-code', { email, code });
  }

  // 绑定第三方账号
  async bindThirdPartyAccount(provider: string, code: string): Promise<void> {
    return apiService.post('/auth/bind-third-party', { provider, code });
  }

  // 解绑第三方账号
  async unbindThirdPartyAccount(provider: string): Promise<void> {
    return apiService.post('/auth/unbind-third-party', { provider });
  }

  // 获取用户权限列表
  async getUserPermissions(): Promise<string[]> {
    return apiService.get('/auth/permissions');
  }

  // 获取用户角色列表
  async getUserRoles(): Promise<string[]> {
    return apiService.get('/auth/roles');
  }

  // 检查用户权限
  hasPermission(permission: string): boolean {
    const authStore = useAuthStore.getState();
    return authStore.hasPermission(permission);
  }

  // 检查用户角色
  hasRole(role: string): boolean {
    const authStore = useAuthStore.getState();
    return authStore.hasRole(role);
  }

  // 获取当前用户
  getCurrentUserFromStore(): User | null {
    const authStore = useAuthStore.getState();
    return (authStore.user as User) || null;
  }

  // 检查是否已登录
  isAuthenticated(): boolean {
    const authStore = useAuthStore.getState();
    return authStore.isAuthenticated;
  }

  // 获取当前Token
  getToken(): string | null {
    const authStore = useAuthStore.getState();
    return authStore.token;
  }
}

export const authService = new AuthService();